import 'package:demo/pages.dart';
import 'package:demo/routers.dart';
import 'package:flutter/material.dart';

class RouterNavigatorObserver extends NavigatorObserver {
  static final List<String> _pages = [];

  @override
  void didPush(Route route, Route? previousRoute) {
    super.didPush(route, previousRoute);
    debugPrint("RouterNavigatorObserver.didPush():${route.settings.name}--${previousRoute?.settings.name}");
    Routers.curRoute = route;
    _addRoute(route.settings.name);
    debugPrint("RouterNavigatorObserver.didPush() _pages:$_pages");
  }

  @override
  void didReplace({Route? newRoute, Route? oldRoute}) {
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    debugPrint("RouterNavigatorObserver.didReplace():${newRoute?.settings.name}--${oldRoute?.settings.name}");
    _removeRoute(oldRoute?.settings.name);
    _addRoute(newRoute?.settings.name);
    debugPrint("RouterNavigatorObserver.didReplace() _pages:$_pages");
  }

  @override
  void didRemove(Route route, Route? previousRoute) {
    super.didRemove(route, previousRoute);
    debugPrint("RouterNavigatorObserver.didRemove():${route.settings.name}--${previousRoute?.settings.name}");
    _removeRoute(route.settings.name);
    debugPrint("RouterNavigatorObserver.didRemove() _pages:$_pages");
  }

  @override
  void didPop(Route route, Route? previousRoute) {
    super.didPop(route, previousRoute);
    debugPrint("RouterNavigatorObserver.didPop():${route.settings.name}--${previousRoute?.settings.name}");
    Routers.curRoute = previousRoute;
    Routers.unfocus();
    _removeRoute(route.settings.name);
    debugPrint("RouterNavigatorObserver.didPop() _pages:$_pages");
  }

  void _addRoute(String? routeName) {
    if (routeName != null && routeName.isNotEmpty) {
      _pages.add(routeName);
    }
  }

  void _removeRoute(String? routeName) {
    if (routeName != null && routeName.isNotEmpty) {
      _pages.remove(routeName);
    }
  }

  static bool hasMain() {
    bool hasMain = _pages.contains(Pages.main);
    debugPrint("RouterNavigatorObserver.hasMain:$hasMain");
    return hasMain;
  }

  static bool hasPage(String path) {
    bool hasPage = _pages.contains(path);
    debugPrint("RouterNavigatorObserver.hasPage:$hasPage -- $path");
    return hasPage;
  }

  static bool lastPage() {
    bool lastPage = _pages.length == 1;
    debugPrint("RouterNavigatorObserver.lastPage:$lastPage length:${_pages.length} pages:${_pages.toString()}");
    return lastPage;
  }

  static int pageLength() {
    return _pages.length;
  }
}
